package com.overlord.im.client.netty.handler;

import com.overlord.im.commons.constant.AckType;
import com.overlord.im.commons.constant.MsgType;
import com.overlord.im.commons.constant.OverlordImConstants;
import com.overlord.im.commons.constant.SystemType;
import com.overlord.im.commons.message.OverlordImMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wuwei
 * @className ClientHeartBeatHandler
 * @description
 * @date 2020-05-30 15:25
 **/
@Slf4j
public class ClientHeartBeatHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.WRITER_IDLE) {
                log.info("客户端向服务端发送心跳");
                ctx.writeAndFlush(heartBeat());
            }
        }
        super.userEventTriggered(ctx, evt);
    }

    private OverlordImMessage heartBeat() {
        OverlordImMessage build =
                OverlordImMessage.builder().msgType(MsgType.SYSTEM).ackType(AckType.NONE).systemType(SystemType.HEART_BEAT)
                        .clientMessageId(OverlordImConstants.NONE_MESSAGE_ID).sequenceId(OverlordImConstants.NONE_MESSAGE_ID)
                        .version(OverlordImConstants.OVERLORD_IM_VERSION).build();
        return build;
    }
}
